package com.github.cakin.shiro.chapter2.realm;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.realm.Realm;

/**
 * @className: MyRealm2
 * @description: 自定义Realm
 * @date: 2020/5/16
 * @author: cakin
 */
public class MyRealm2 implements Realm {
    /**
     * 功能描述：返回一个唯一的Realm名字
     *
     * @author cakin
     * @date 2020/5/16
     * @return String
     */
    public String getName() {
        return "myrealm2";
    }

    /**
     * 功能描述：判断此Realm是否支持UsernamePasswordToken
     *
     * @param token 用户token
     * @author cakin
     * @date 2020/5/16
     * @return boolean 是否支持
     */
    public boolean supports( AuthenticationToken token ) {
        return token instanceof UsernamePasswordToken; // 仅支持UsernamePasswordToken类型的Token
    }

    /**
     * 功能描述：根据Token获取认证信息
     *
     * @author cakin
     * @date 2020/5/16
     * @param token token
     * @throws AuthenticationException 认证异常
     * @return AuthenticationInfo 认证信息
     */
    public AuthenticationInfo getAuthenticationInfo( AuthenticationToken token ) throws AuthenticationException {

        String username = (String) token.getPrincipal(); //得到用户名
        String password = new String((char[]) token.getCredentials()); // 得到密码
        if (!"zhangsan".equals(username)) {
            throw new UnknownAccountException(); // 如果用户名错误
        }
        if (!"123".equals(password)) {
            throw new IncorrectCredentialsException(); // 如果密码错误
        }
        // 如果身份认证验证成功，返回一个AuthenticationInfo实现
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
